/*eslint-disable */
@Inject('$log', '$rootScope', '$scope', '$state', 'ngDialogService', 'previewTableService', 'processTableService', 'ngDialog', 'box')
class ProcessTableController {
  constructor() {
    this.view = {
      isReadonly: true,
      key: null,
      status: 'create', // create  submit  audit complete
      nextUserids: null,
      tableId: this.$state.tableId,
    };

    this.tableId = this.$state.params.tableId;

    this.boxType = [];
    if (box.children && box.children.length > 0) {
      this.boxType = box.children;
    } else {
      this.boxType.push(box);
    }

    this.boxId = box.id;

    this.adviceModule ={
      confirmInfo: '',
      nextNodeUserids: null,
      workItemid: this.$state.params.todoId,
    };

    this.data = {
      contractingUnit: '', // 承包单位
      supervisionUnit: '', // 监理单位
      contractNo: '', // 合同号
      no: '', // 编号
      projectName: '', // 项目名称
      auditContentName: '', // 审查内容名称
      superiorAdvice: '', // 监理审查意见
      viceEngineer: '', // 安全副总监/专业监理工程师
      viceEngineerSignTime: '', // 安全副总监/专业监理工程师签字时间
      viceEngineerSignTimeStr: '',
      engineerAdvice: '', // 总监理工程师意见
      engineer: '', // 总监理工程师
      engineerSignTime: '', // 总监理工程师签字时间
    };
    this.init();

    this.$getTemplate();

    $scope.$watch('vm.view.status', (newValue) => {
      if (newValue === 'submit') {
        this.view.isReadonly = false;
      }
    })

    this.$isCanAction();
  }

  init() {
    this.view.status = this.$state.current.name == 'processTableTodo' ? 'audit' : 'create';
  }

  // 获取模板
  $getTemplate() {
    if (this.$state.params.id) {
      const id = this.$state.params.id;
      this.previewTableService
        .get({ id: id })
        .then((res) => {
          // 获取流程
          this.view.key = res.data.template;
          this.$getProcess();
        });
      } else {
        this.$getProcess();
        this.getDetailTable();
      }
  }

  // 获取流程
  $getProcess() {
    if(this.view.status == 'create' || this.view.status == 'submit' ) {
      const flowKey = this.view.key;
      this.processTableService.getFlow(flowKey).then((res) => {
        if (res.success) {
          this.processList = res.data.flowNodeList;
        }
      });
    } else {
      const param = {
        mapParams: {
          piId: this.$state.params.piId,
        }
      };
      this.processTableService.queryFlowNode(param).then((res) => {
        if (res.success) {
          this.processList = res.rows;
          const length = this.processList.length;
          this.processList.forEach((item, index) => {
            if (index === 0 && item.currentNode) {
              this.view.status = 'submit';
            } else if (index === length - 1 && item.currentNode) {
              this.view.status = 'complete';
            } else if (item.currentNode) {
              this.view.status = 'audit';
            }

            if (item.nodeKey === 'end' && item.currentNode) {
              this.isShowBtn = true;
            } else {
              this.isShowBtn = false;
            }
          });
        }
      });
    }
  }

  // 判断是否可执行
  $isCanAction() {
    if (!this.$state.params.todoId) {
      this.isCanOperate = true;
      return false;
    }
    const id = this.$state.params.todoId;
    this.previewTableService
      .getCanAction({ workItemId: id })
      .then((res) => {
        this.isCanOperate = res.success;
      });
  }


  // 点击创建
  $createProcess() {
    this.view.status = 'submit';
  }

  // 提交
  $submitTable() {
    this.data.flowKey = this.view.key;
    this.data.nextUserids = this.view.nextUserids;
    if (this.data && this.data.id) {
      this.data.workItemid = this.$state.params.todoId;
      this.data.actionType = 'agree';
      this.processTableService
        .update(this.data)
        .then((res) => {
          if (res.success) {
            this.view.nextUserids = null;
            this.view.tableId = res.data.id;
            // 跳转详情
            this.$state.go('processTableDetail', {
              piId: res.data.piId,
              tableId: res.data.id,
              name: '方案审查',
            });
          }
        });
    } else {
      this.processTableService
        .add(this.data)
        .then((res) => {
          if (res.success) {
            this.view.nextUserids = null;
            this.view.tableId = res.data.id;
            // 跳转详情
            this.$state.go('processTableDetail', {
              piId: res.data.piId,
              tableId: res.data.id,
              name: '方案审查',
            });
          }
        });
    }

  }

  // 查询表格数据
  getDetailTable() {
    const id = this.view.tableId ? this.view.tableId : this.$state.params.tableId;
    this.processTableService
      .get(id)
      .then((res) => {
        if (res.success) {
          this.data = res.data;
        }
      });
  }

  // 同意不同意提交意见
  submitAdvice(operatName) {
    this.adviceModule.actionType = operatName;
    this.adviceModule.nextNodeUserids = this.view.nextUserids;
    this.processTableService.queryFind(this.adviceModule)
    .then((res) => {
      if(res.success) {
        this.view.nextUserids = null;
        this.getDetailTable();
        this.$getProcess();
        window.history.go(-1);
      } else {
        this.ngDialogService.alertError(res.message);
      }
    });
  }

  // 流转记录
  $transferRecordDialog(ctrl) {
    this.ngDialog.open({
      template: 'transferRecord',
      className: 'ngdialog-theme-default pa-confirm-theme pa-confirm-self systemManage-add-dialog record-dialog',
      controllerAs: 'vm',
      controller($rootScope, $scope, $state, ngDialogService) {
        'ngInject';

        this.$table = {
          fetchTimes: 0,
          isTableLoading: false,
          pagination: {
            ITEMS_PER_PAGE: 5,
            MAX_SIZE: 5,
            currentPage: 1,
            total: 0,
          },
        };
        this.query = () => {
          ctrl.processTableService
          .queryConfirmList({
            mapParams: { piId: ctrl.piId },
            page: this.$table.pagination.currentPage,
            size: this.$table.pagination.ITEMS_PER_PAGE,
          })
          .then((res) => {
            if (res.success) {
              this.recordList = res.rows;
              this.$table.pagination.totalItems = res.total;
              this.$table.pagination.total = res.total;
              this.$table.isTableLoading = false;
              if (res.total < 1) {
                this.$table.fetchTimes += 1;
              }
            } else {
              ngDialogService.alertError(res.message);
            }
          });
        }
        this.query();
      },
    });
  }

  $print() {
    $('.qr-print').print({ globalStyles: false, timeout: 1200 });
  }

  // 资料归档
  $mobileDocument(ctrl) {
    this.ngDialog.open({
      template: 'dataArchiving',
      className: 'ngdialog-theme-default pa-confirm-theme pa-confirm-self systemManage-add-dialog',
      controllerAs: 'vm',
      controller($rootScope, $scope, ngDialogService, documentService) {
        'ngInject';

        this.view = {
          attachmentFiles: [],
        };

        this.boxType = angular.copy(ctrl.boxType);

        this.document = {
          orgId: $rootScope.orgId || storageApi.get('orgId'),
          documentName: '',
          documentNumber: '',
          compileTime: '',
          remark: '',
          attachmentIds: [],
          documentSourceId: ctrl.tableId,
          // templateId: ctrl.piId,
          type: ctrl.boxId,
          documentSourceType: 2,
        };

        this.document.compileTime = new Date();

        this.submitForm = () => {
          this.document.attachmentIds = this.view.attachmentFiles.map(item => item.id);
          documentService.save(this.document)
            .then((res) => {
              if (res.success) {
                ngDialogService.alertSuccess(res.message);
                $scope.closeThisDialog();
              } else {
                ngDialogService.alertError(res.message);
              }
            });
        };
      },
    });
  }

}

export default ProcessTableController;
